package com.alexsun.smarthome

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.CompoundButton
import android.widget.Switch
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
import java.util.*

class ControlActivity : AppCompatActivity(), CompoundButton.OnCheckedChangeListener {

    private val BASE_URL = "http://139.196.222.129:8081"
    private val timer: Timer = Timer()
    private var temp = ""
    private var humd = ""
    private var mq = ""
    private var light = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_control)
        findViewById<Switch>(R.id.switch_led).setOnCheckedChangeListener(this)
        findViewById<Switch>(R.id.switch_curtain).setOnCheckedChangeListener(this)
        findViewById<Switch>(R.id.switch_fan).setOnCheckedChangeListener(this)
        findViewById<Switch>(R.id.switch_air).setOnCheckedChangeListener(this)
        val task: TimerTask = object : TimerTask() {
            override fun run() {
                val json = JSONObject()
                val body = json.toString().toRequestBody("application/json".toMediaTypeOrNull());
                val request = Request.Builder()
                    .url("$BASE_URL/messages/summary")
                    .method("POST", body)
                    .build()

                OkHttpClient().newCall(request).enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        Looper.prepare();
                        Toast.makeText(this@ControlActivity, "数据请求失败！", Toast.LENGTH_SHORT).show()
                        Log.e("POST", e.toString())
                        Looper.loop();
                    }

                    override fun onResponse(call: Call, response: Response) {
                        val responseJson = JSONObject(response.body?.string() ?: "")
                        val code = responseJson["code"]
                        if (code == 0) {
                            temp = responseJson.getJSONObject("data").get("temp") as String
                            humd = responseJson.getJSONObject("data").get("humd") as String
                            mq = responseJson.getJSONObject("data").get("mq") as String
                            light = responseJson.getJSONObject("data").get("light") as String
                        } else {
                            Looper.prepare();
                            Toast.makeText(this@ControlActivity, "数据请求失败！", Toast.LENGTH_SHORT).show()
                            Looper.loop();
                        }
                    }
                })

                runOnUiThread(Runnable {
                    findViewById<TextView>(R.id.textTemp).text = "温度 $temp"
                    findViewById<TextView>(R.id.textHumd).text = "湿度 $humd"
                    findViewById<TextView>(R.id.textMQ).text = "烟雾 $mq"
                    findViewById<TextView>(R.id.textLight).text = "光照 $light"
                })
            }
        }
        timer.schedule(task, 0, 3000);
    }

    override fun onCheckedChanged(v: CompoundButton?, value: Boolean) {
        val message = if (value) "1" else "0"
        var topic = ""
        var deviceID = 0

        when(v?.id) {
            R.id.switch_led -> {
                topic = "Home/Device/LED"
                deviceID = 5
            }
            R.id.switch_fan -> {
                topic = "Home/Device/Fan"
                deviceID = 6
            }
            R.id.switch_curtain -> {
                topic = "Home/Device/Curtain"
                deviceID = 7
            }
            R.id.switch_air -> {
                topic = "Home/Device/Air"
                deviceID = 8
            }
        }
        val json = JSONObject()
        json.put("topic", topic)
        json.put("message", message)
        val body = json.toString().toRequestBody("application/json".toMediaTypeOrNull());
        val request = Request.Builder()
            .url("$BASE_URL/devices/${deviceID}/control")
            .method("POST", body)
            .build()

        OkHttpClient().newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Looper.prepare();
                Toast.makeText(this@ControlActivity, "请求失败！", Toast.LENGTH_SHORT).show()
                Log.e("POST", e.toString())
                Looper.loop();
            }
            override fun onResponse(call: Call, response: Response) {
                val responseJson = JSONObject(response.body?.string() ?: "")
                val code = responseJson["code"]
                if (code == 0) {
                    Looper.prepare();
                    Toast.makeText(this@ControlActivity, "发送成功！", Toast.LENGTH_SHORT).show()
                    Looper.loop();
                } else {
                    Looper.prepare();
                    Toast.makeText(this@ControlActivity, "发送失败！", Toast.LENGTH_SHORT).show()
                    Looper.loop();
                }
            }
        })
    }
}